# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.

from odoo import tools
from odoo import api, fields, models


class InvoicePaymentReport(models.Model):
    _name = "invoice.payment.report"
    _description = "Invoice Payment Report"
    _auto = False
    _order = 'number desc'

    # name = fields.Char('Order Reference', readonly=True)
    number = fields.Char(u'发票号码', readonly=True)
    partner_id = fields.Many2one('res.partner', u'客户名称', readonly=True)
    date_invoice = fields.Date(u'发票日期', readonly=True)
    amount_total_signed = fields.Float(u'发票金额(含税)', readonly=True)
    date_due = fields.Date(u'到期日', readonly=True)
    residual_signed = fields.Float(u'待收款金额', readonly=True)
    payment_date = fields.Char(u'实际收款日', readonly=True)
    payment_amt = fields.Float(u'已收款金额', readonly=True)

    @api.model_cr
    def init(self):
        tools.drop_view_if_exists(self.env.cr, self._table)
        self.env.cr.execute("""CREATE or REPLACE VIEW %s as (
SELECT id,
       number,
       date_invoice,
       partner_id,
       amount_total_signed,
       date_due,
       residual_signed,
       payment_amt,
       array_to_string(array_agg(payment_date ORDER BY payment_date), ', ') AS payment_date
FROM (SELECT ai.id,
             ai.number,
             ai.date_invoice,
             ai.partner_id,
             ai.amount_total_signed,
             ai.date_due,
             ai.residual_signed,
             ai.amount_total_signed - ai.residual_signed AS payment_amt,
             ap.payment_date
      FROM account_invoice ai
      LEFT JOIN account_invoice_payment_rel aip ON ai.id = aip.invoice_id
      LEFT JOIN account_payment ap ON aip.payment_id = ap.id
      WHERE ai.number IS NOT NULL) A
GROUP BY id, number, date_invoice, partner_id, amount_total_signed, date_due, residual_signed, payment_amt
            )""" % self._table)
